package com.cloudcc.mobile.dao;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Xml;
import android.widget.RemoteViews;

import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.UpdataInfo;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.util.DialogUtils.OnDoClickListener;
import com.cloudcc.mobile.util.FileUtil;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.PackageUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * 更新版本
 * @author Administrator
 *
 */
public class UpdateDao {
	private DefaultHttpClient httpClient;
	private NotificationManager manager;
	private Notification notif;
	private int len;
	private static String path=Tools.getImagePath("/CloudCC/FuJian/");
	private static String name;

	/**
	 * 解析更新信息
	 * @param in
	 * @throws IOException
	 */

	public void update(final Context context,final boolean isShow){
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET,UrlTools.updateUrl,
				new RequestCallBack<String>(){
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				LogUtils.d("app", "更新获取信息成功");
				String updateInfo = responseInfo.result;
				ByteArrayInputStream in = null;
				try {
					in = new ByteArrayInputStream(updateInfo.getBytes("utf-8"));
					final UpdataInfo info =UpdateDao.getUpdataInfo(in);
					name=info.getName();
					PackageUtils pack=new PackageUtils(context);
					String appVersion = pack.getVersionName();
					if(!info.getVersion().equals(appVersion)){
						DialogUtils dialog=new DialogUtils(context);
						dialog.showUpdateAppDialog(context, "更新程序", info.getDescription());
						dialog.setOnDoClicktListener(new OnDoClickListener() {
							@Override
							public void confirm() {
								updateAPK(info.getUrl(), context);
							}

							@Override
							public void cancel() {
								
							}
						});
					}else{
						if(isShow){
							Tools.showInfo(context, "您已经是最新版本！");
						}
					}
				} catch (Exception e) {
					Tools.handle(e);
				}
			}
			@Override
			public void onStart() {
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				LogUtils.d("app", "更新失败");
			}
		});
	}

	/*
	 * 用pull解析器解析服务器返回的xml文件 (xml封装了版本号)
	 */
	public static  UpdataInfo getUpdataInfo(InputStream is) throws Exception{
		XmlPullParser  parser = Xml.newPullParser();  
		parser.setInput(is, "utf-8");//设置解析的数据源 
		int type = parser.getEventType();
		UpdataInfo info = new UpdataInfo();//实体
		while(type != XmlPullParser.END_DOCUMENT ){
			switch (type) {
			case XmlPullParser.START_TAG:
				if("version".equals(parser.getName())){
					info.setVersion(parser.nextText());	//获取版本号
				}else if ("url".equals(parser.getName())){
					info.setUrl(parser.nextText());	//获取要升级的APK文件
				}else if ("name".equals(parser.getName())){
					info.setName(parser.nextText());	//获取要升级的APK文件
				}
				else if ("description".equals(parser.getName())){
					info.setDescription(parser.nextText());	//获取该文件的信息
				}
				break;
			}
			type = parser.next();
		}
		return info;
	}


	@SuppressWarnings({ "unused", "rawtypes" })
	public void updateAPK(String apkUrl,final Context context){
		notification(context);
		String filePathName=path+"/"+name;
		File file=new File(filePathName);
		if(file.exists()){
			FileUtil.deleteFile(file);
		}
		HttpUtils http = new HttpUtils();
		httpClient=(DefaultHttpClient)http.getHttpClient(); 
		httpClient.addRequestInterceptor(null);
		if(path==null){
			Tools.showInfo(context, "没有sd卡，或者内存不足！");
			return ;
		}
		HttpHandler httphandler = 
				http.download(apkUrl, path+"/"+name, true, // 如果目标文件存在，接着未完成的部分继续下载。
						false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
						new RequestCallBack<File>() { 

					@Override
					public void onSuccess(ResponseInfo<File> arg0) {
						NotificationUtils.clearNotification(context, 1000);
						installApk(new File(path+"/"+name), context);
					} 
					@Override
					public void onStart() {
						super.onStart();
					}	
					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						Message msg = new Message();  
						msg.what = 1000;  
						msg.obj = current; 
						Tools.i("loadhandler", "总大小："+total);
						Tools.i("loadhandler", "已经下载："+current);
						loadhandler.sendMessage(msg);  
						len=(int) (current*100/total);
						if(current == total){  
							loadhandler.sendEmptyMessage(-2);  
						}  
						super.onLoading(total, current, isUploading);
					}
					@Override
					public void onFailure(HttpException arg0, String arg1) {

					}
				});
	}

	/**
	 * 下载通知
	 */
	protected void notification(Context context) {
		manager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);  
		notif = new Notification();  
		notif.icon = R.drawable.chatter_download;  
		notif.tickerText = "更新版本...";  
		notif.flags |=Notification.FLAG_AUTO_CANCEL;
		notif.flags |= Notification.FLAG_SHOW_LIGHTS; 
		//通知栏显示所用到的布局文件  
		notif.contentView = new RemoteViews(context.getPackageName(), R.layout.loading_notification);  
		notif.contentIntent = null;  
		notif.contentView.setTextViewText(R.id.loadingName, "正在下载("+name+")");  
		manager.notify(1000, notif);
	}

	private Handler loadhandler = new Handler(){  
		@Override  
		public void handleMessage(Message msg) {  
			super.handleMessage(msg);  
			if(msg.what==1000){
				notif.contentView.setTextViewText(R.id.content_view_text1, len+"%");  
				notif.contentView.setProgressBar(R.id.content_view_progress, 100, len, false);  
				if(len==100){
					notif.contentView.setTextViewText(R.id.loadingName, "下载完成("+name+")！"); 
				}
				manager.notify(1000, notif);  
			}
		}  
	}; 
	//安装apk   
	protected void installApk(File file,Context context) {  
		Intent intent = new Intent();  
		//执行动作  
		intent.setAction(Intent.ACTION_VIEW);  
		//执行的数据类型  
		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");  
		context.startActivity(intent);  
	}  
}
